package com.ruoyi.data.filter.second.service;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.data.filter.second.entity.ApiRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DefaultApiAuthencatorImpl implements ApiAuthencator {

    @Autowired
    private DataAppService dataAppService;

    @Override
    public int  auth(ApiRequest apiRequest, ServletRequest request , ServletResponse response) {
        Long appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        long timeStamp = apiRequest.getTimeStamp();

        String appKey = dataAppService.selectAppKeyByAppId(appId);

        if(appKey == null || appKey == ""){
            int code = 503;
            String msg = StringUtils.format("请输入正确的key值", ((HttpServletRequest)request).getRequestURI());
            ServletUtils.renderString((HttpServletResponse) response, JSON.toJSONString(AjaxResult.error(code, msg)));
            return code;
        }

        AuthToken clientAuthToken = new AuthToken(token, timeStamp);
        if (clientAuthToken.isExpired()) {

            int code = 502;
            String msg = StringUtils.format("token 已过期", ((HttpServletRequest)request).getRequestURI());
            ServletUtils.renderString((HttpServletResponse) response, JSON.toJSONString(AjaxResult.error(code, msg)));
            return code;
        }

        AuthToken serverAuthToken = AuthToken.generateToken(appId, appKey, timeStamp);
        if (serverAuthToken == null || !serverAuthToken.isMatched(clientAuthToken)) {
            int code = 501;
            String msg = StringUtils.format("您无权访问该接口", ((HttpServletRequest)request).getRequestURI());
            ServletUtils.renderString((HttpServletResponse) response, JSON.toJSONString(AjaxResult.error(code, msg)));

            return code;
        }

        return 1;

    }
}
